const wxHttpHandler = require('../../utils/wxHttpHandler.js');
const api = require('../../APIConfig/apiConfig.js');

Page({
  data: {
    commNo: '',
    deviceTypes: [], //设备类型
    date: '请选择服务到期日',
    deviceTypes: [], //设备类型
    selectDeviceType: '请选择设备类型', //选中的设备类型
    selectDeviceTypeId: -1, //选中的设备类型
  },

  onLoad: function (options) {
    this.loadTerminalkind1()
  },

  onShow: function () {},

  commNoInput: function (e) {
    this.setData({
      commNo: e.detail.value
    })
  },


  // 设备类型选择器
  bindDeviceTypeChange: function (e) {
    this.setData({
      selectDeviceTypeId: this.data.deviceTypes[e.detail.value].id,
      selectDeviceType: this.data.deviceTypes[e.detail.value].name
    })
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },


  // 提交
  submit: function () {
    wx.showModal({
      title: '添加设备',
      content: '您确定提交设备数据吗？',
      confirmText: '提交',
      success(res) {
        if (res.confirm) {
          that.saveTerminal()
        }
      }
    })

  },


  //设备类型列表
  loadTerminalkind1: function () {

    let data = {}
    const that = this
    wxHttpHandler({
      type: 'post',
      path: api.loadTerminalkind1,
      data: data,
      fn: function (res) {
        wx.hideLoading()
        if (res.code == 0) {
          if (res.data != null) {
            that.setData({
              deviceTypes: res.data
            })
          }
        } else {
          wx.showToast({
            title: res.desc,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
      }

    })
  },


  //新增设备
  saveTerminal: function () {

    if (this.data.commNo == '') {
      wx.showToast({
        title: '请输入设备通讯号',
      })
      return
    }

    if (this.data.selectDeviceTypeId == -1) {
      wx.showToast({
        title: '请选择设备类型',
      })
      return
    }

    if (this.data.date == '请选择服务到期日') {
      wx.showToast({
        title: '请选择服务到期日',
      })
      return
    }


    let data = {
      commNo: this.data.commNo,
      workUnitID: wx.getStorageSync('workUnitID'),
      terminalKindID: this.data.selectDeviceTypeId,
      overTime: this.data.date
    }
    const that = this
    wx.showLoading()
    wxHttpHandler({
      type: 'get',
      path: api.saveTerminal,
      data: data,
      fn: function (res) {
        wx.hideLoading()
        if (res.code == 0) {
          wx.showToast({
            title: '已新增',
          })
        } else {
          wx.showToast({
            title: res.desc,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
      }

    })
  },
})